package com.xxl.job.admin.core.trigger;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: Zhihj
 * @Date: 2023-10-15 22:17:09
 */
public class XxlJobTrigger {
    private static Logger logger = LoggerFactory.getLogger(XxlJobTrigger.class);
    /**
     * trigger job
     *
     * @param jobId
     * @param triggerType
     * @param failRetryCount
     * 			>=0: use this param
     * 			<0: use param from job info config
     * @param executorShardingParam
     * @param executorParam
     *          null: use job param
     *          not null: cover job param
     * @param addressList
     *          null: use executor addressList
     *          not null: cover
     */
    public static void trigger(int jobId,
                               TriggerTypeEnum triggerType,
                               int failRetryCount,
                               String executorShardingParam,
                               String executorParam,
                               String addressList) {
        //// load data  获取具体的job信息
        XxlJobInfo xxlJobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(jobId);
        if(xxlJobInfo == null){
            logger.warn(">>>>>>>>>>>> trigger fail, jobId invalid，jobId={}",jobId);
            return;
        }
        if(executorParam != null){
            xxlJobInfo.setExecutorParam(executorParam);
        }
        //获取重试次数
        int finalfailRetryCount = failRetryCount>=0?failRetryCount:xxlJobInfo.getExecutorFailRetryCount();
        XxlJobGroup group =XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(xxlJobInfo.getJobGroup());
        // cover addressList
        if(addressList!=null && addressList.trim().length()>0){
            //执行器地址类型：0=自动注册、1=手动录入
            group.setAddressType(1);
            group.setAddressList(addressList.trim());
        }
        //sharding param
        int[] shardingParam = null;
        if(executorShardingParam != null){
            String[] shardingArr = executorShardingParam.split("/");
            if(shardingArr.length == 2 && isNumeric(shardingArr[0]) && isNumeric(shardingArr[1])){
                shardingParam = new int[2];
                shardingParam[0] = Integer.valueOf(shardingArr[0]);
                shardingParam[1] = Integer.valueOf(shardingArr[1]);
            }
        }


    }
    private static boolean isNumeric(String str){
        try {
            int result = Integer.valueOf(str);
        }catch (NumberFormatException e){
            return false;
        }
        return true;
    }
}
